package com.woniuxy.purchase.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import com.woniuxy.purchase.entity.pojo.DemandGoods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class HotGoodsThread {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Async
    public void addHotGoods(List<DemandGoods> list) {
        log.info("开始向redis中添加数据,{}", list);
        String key = getCurrentDate();
        log.info("keys,{}", key);
        for (DemandGoods demandGoods : list) {
            //如果不存在,则把kv保存到redis中,如果存在则该kv的 score+=score
            redisTemplate.opsForZSet().incrementScore(key, demandGoods.getGoodsNumber(), demandGoods.getQuantity());
        }
        redisTemplate.expire(key, 30, TimeUnit.DAYS);
    }

    public String getCurrentDate() {
/*        LocalDateTime now = LocalDateTime.now();
        String year = String.valueOf(now.getYear());
        String month = String.format("%02d", now.getMonthValue());
        String day = String.format("%02d", now.getDayOfMonth());*/
        Calendar calendar = Calendar.getInstance();
         int year = calendar.get(Calendar.YEAR);
         int month = calendar.get(Calendar.MONTH)+1;
         int day = calendar.get(Calendar.DATE);
        log.info("存,{}",year + ":" + month + ":" + day + "/" + "goods");
        if(month < 10){
            return year + ":" +  "0" + month + ":" + day + "/" + "goods";
        }
        return year + ":" + month + ":" + day + "/" + "goods";
    }

    public List<DemandGoods> getHotDateByCurrentDate(String currentDate) {
        currentDate += "/goods";
        currentDate = StringUtils.replace(currentDate, "-", ":");
        log.info("取,{}",currentDate);
        Set<ZSetOperations.TypedTuple<Object>> set = redisTemplate.opsForZSet().reverseRangeWithScores(currentDate, 0, 9);
        ArrayList<DemandGoods> list = new ArrayList<>();
        for (ZSetOperations.TypedTuple<Object> objectTypedTuple : set) {
            String goodsNumber = Convert.toStr(objectTypedTuple.getValue());
            Integer quantity = Convert.toInt(objectTypedTuple.getScore());
            list.add(new DemandGoods(goodsNumber, quantity));
        }
        log.info("热点数据前10,{}", list);
        return list;
    }
}
